//
//  YJLtabBar.m
//  YJL
//
//  Created by tlian on 15/4/20.
//  Copyright (c) 2015年 tlian. All rights reserved.
//

#import "YJLtabBar.h"
#import "YJLTabBarButton.h"

@interface YJLtabBar ()

@property (nonatomic, strong) NSMutableArray *tabBarButtons;
@property (nonatomic, weak) YJLTabBarButton *selectedButton;

@end

@implementation YJLtabBar


-(NSMutableArray *)tabBarButtons{
    if (_tabBarButtons == nil) {
        _tabBarButtons = [NSMutableArray array];
    }
    return _tabBarButtons;
}

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

-(void)addTabBarButtonWithItem:(UITabBarItem *)item{
    // 创建新按钮
    YJLTabBarButton *button = [[YJLTabBarButton alloc] init];
    [self addSubview:button];
    // 添加按钮到数组中
    [self.tabBarButtons addObject:button];
    
    // 设置数据
    button.item = item;
    
    // 监听按钮点击
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    
    // 默认选中第0个按钮
    if (self.tabBarButtons.count == 1) {
        [self buttonClick:button];
    }
}

/**
 *  监听按钮点击
 */
- (void)buttonClick:(YJLTabBarButton *)button
{
    // 1.通知代理
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectedButtonFrom:to:)]) {
        [self.delegate tabBar:self didSelectedButtonFrom:self.selectedButton.tag to:button.tag];
    }
    
    // 2.设置按钮的状态
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
}

-(void)layoutSubviews{
    [super layoutSubviews];
   // 按钮frame数据
    
    CGFloat buttonY = 0;
    CGFloat buttonW = self.frame.size.width / self.subviews.count;
    CGFloat buttonH = self.frame.size.height;
    for (int i = 0; i < self.tabBarButtons.count; i++) {
        //取出按钮
        YJLTabBarButton *button = self.tabBarButtons[i];
        // 设置按钮的frame
        CGFloat buttonX = i * buttonW;
//        if (i > 1) {
//            buttonX
//        }
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        // 绑定tag
        button.tag = i;
    }
}

@end
